const Api = require("../libs/api");
let tokenjson = require("./token.json");
let gitee = new Api.GiteeApiOnRepo(tokenjson['token'], "patricia_of_end", "nyaa-literature");
const Worktile = require("lib-worktile/lib").web.WorktileWeb;
const json_beautify = require("json-beautify");

let boot = async () => {
  let o_worktileIns = await Worktile.getValidWorktileInstance("hujimiya", "18390921465", "work65huji")
  if (!o_worktileIns.ok) {
    debugger
  }
  let wt = o_worktileIns.instance;
  while (true) {
    let o_find = await gitee.findIssueByStateAndMileStone("pending","open",0,60);
    'debugger'
    if (o_find.ok) {
      if(o_find.issues.length==0){
        debugger
        return;
      }
      for (let issue_number of o_find.issues.map(i => i.number)) {
        let o_qi = await gitee.queryIssueByNumber(issue_number);
        if (!o_qi.ok) {
          debugger
          continue;
        }
        let body = o_qi.issue.body;
        let body_obj = JSON.parse(body);
        let id = body_obj['id'];
        let o_search = await wt.getTasksInListViewByTitleKeyword(
          '5be8ee7f3281d027c4233e9e',
          '5be8ee7f3281d027c4233e9f',
          id
        );
        if (!o_search.ok) {
          debugger
          continue;
        }
        let such_tasks = o_search.data.value.filter(task => task.title.startsWith(id));
        if (!such_tasks.length) {
          let o_createTask = await wt.createTaskToKanban(
            `5be8ee7f3281d027c4233e8f`,
            '5be8ee7f3281d027c4233ea0',
            `${id}||${body_obj.title}`,
            json_beautify(body_obj, null, 3, 20),
            ['5be96642d9c687271ef4548b']
          )
          if(!o_createTask.ok){
            debugger
            continue;
          }
        }
        let o_changeMilestone = await gitee.changeIssueMilestone(issue_number, 15222);
        if (!o_changeMilestone.ok) {
          debugger
          continue
        }
      }
    }else{
      debugger
      continue
    }
  }
};


boot();